package cn.pconline.autoclub.web;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.gelivable.auth.GeliAuthFacade;
import org.gelivable.auth.entity.GeliFunction;
import org.gelivable.auth.entity.GeliSession;
import org.gelivable.web.Env;
import org.gelivable.web.EnvUtils;
import org.gelivable.web.HttpMethod;

/**
 *
 * @author chenxiaohu
 */
public class AuthFilter implements Filter {

    private Log log = LogFactory.getLog(AuthFilter.class);
    //后台
    private static final String DEV_CODE = "A1002";
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");//post提交ISO8859-1转utf-8
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String uri = req.getRequestURI();
        Env env = EnvUtils.getEnv();
        if (log.isDebugEnabled()) {
            log.debug("AuthFilter process: " + uri);
        }

        HttpMethod method = env.getHttpMethod();
        GeliAuthFacade authFacade = env.getBean(GeliAuthFacade.class);

        String adminPrefix = env.getServletContext().getContextPath() + "/admin";
        if (uri.startsWith(adminPrefix + "/geli")) {

            if (!authFacade.isAdmin()) {
                if (method == HttpMethod.POST) {
                    sendAuthFail(resp, true);
                } else {
                    sendAuthFail(resp, false);
                }
                return;
            }
        }
        if (uri.startsWith(adminPrefix)) {
            if (GeliSession.getCurrentUser() == null) {
                sendAuthFail(resp, false);
                return;
            }
            //必须是有后台账号的用户
            if (!authFacade.isApplicationUser(GeliSession.getCurrentUser().getUserId())) {
                if (method == HttpMethod.POST) {
                    sendAuthFail(resp, true);
                } else {
                    sendAuthFail(resp, false);
                }
                return;
            }
        }
       
        if (uri.startsWith(adminPrefix+"/dev")) {
            if (GeliSession.getCurrentUser() == null) {
                sendAuthFail(resp, false);
                return;
            }
            //必须是有后台账号的用户
            if (!authFacade.hasRight(GeliFunction.find(DEV_CODE))) {
                if (method == HttpMethod.POST) {
                    sendAuthFail(resp, true);
                } else {
                    sendAuthFail(resp, false);
                }
                return;
            }
        }
        try {
            chain.doFilter(request, response);
        } catch (Exception e) {
            log.error("权限验证的过滤器出错了", e);
            resp.sendError(404);
            return;
        }
    }

    private void sendAuthFail(HttpServletResponse resp, boolean json) throws IOException {
        if (json) {
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("text/json");
            resp.getWriter().println("{\"statusCode\":300, \"message\":\"没有权限！\"}");
        } else {
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("text/html");
            resp.getWriter().print("<div class=\"pageContent\">"
                    + "<div style='padding-top:200px;text-align:center;"
                    + "font-size:24px;color:red;'>"
                    + "没有权限!</div></div>");
        }
    }
}
